<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学海教育 - 管理员工作台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        :root {
            --primary: #4a6bff;
            --secondary: #6c757d;
            --success: #28a745;
            --warning: #ffc107;
            --danger: #dc3545;
            --light: #f8f9fa;
            --dark: #343a40;
            --border-radius: 8px;
            --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }

        body {
            background-color: #f5f7fb;
            color: #333;
            line-height: 1.6;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 250px;
            background: linear-gradient(to bottom, #4a6bff, #3a5bd9);
            color: white;
            padding: 20px 0;
            box-shadow: var(--box-shadow);
            z-index: 100;
        }

        .logo {
            display: flex;
            align-items: center;
            padding: 0 20px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 20px;
        }

        .logo i {
            font-size: 24px;
            margin-right: 10px;
        }

        .logo h1 {
            font-size: 20px;
        }

        .user-info {
            padding: 0 20px 20px;
            display: flex;
            align-items: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 20px;
            gap: 12px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: rgba(255, 255, 255, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            flex-shrink: 0;
        }
        
        .logout-btn {
            background: rgba(220, 53, 69, 0.8);
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 14px;
            transition: var(--transition);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: auto;
        }
        
        .logout-btn:hover {
            background: rgba(220, 53, 69, 1);
            transform: translateY(-1px);
        }

        .nav-links {
            list-style: none;
        }

        .nav-links li {
            padding: 12px 20px;
            cursor: pointer;
            transition: var(--transition);
            display: flex;
            align-items: center;
        }

        .nav-links li:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .nav-links li.active {
            background-color: rgba(255, 255, 255, 0.2);
        }

        .nav-links i {
            margin-right: 12px;
            font-size: 18px;
        }

        /* 主内容区样式 */
        .main-content {
            flex: 1;
            padding: 30px;
            overflow-y: auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eaeaea;
        }

        .header h2 {
            color: var(--dark);
            font-size: 28px;
            font-weight: 600;
        }

        .action-buttons {
            display: flex;
            gap: 12px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: var(--transition);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background-color: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background-color: #3a5bd9;
            transform: translateY(-1px);
        }

        .btn-outline {
            background-color: transparent;
            color: var(--primary);
            border: 1px solid var(--primary);
        }

        .btn-outline:hover {
            background-color: var(--primary);
            color: white;
        }

        .btn-success {
            background-color: var(--success);
            color: white;
        }

        .btn-success:hover {
            background-color: #218838;
        }

        .btn-danger {
            background-color: var(--danger);
            color: white;
        }

        .btn-danger:hover {
            background-color: #c82333;
        }

        /* 内容区域样式 */
        .content-section {
            display: none;
        }

        .content-section.active {
            display: block;
        }

        .section-title {
            color: var(--dark);
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .section-title i {
            color: var(--primary);
        }

        /* 搜索和筛选 */
        .search-filter {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            gap: 20px;
        }

        .search-box {
            position: relative;
            flex: 1;
            max-width: 400px;
        }

        .search-box input {
            width: 100%;
            padding: 12px 16px 12px 45px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-size: 14px;
            transition: var(--transition);
        }

        .search-box input:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(74, 107, 255, 0.1);
        }

        .search-box i {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--secondary);
        }

        .filter-buttons {
            display: flex;
            gap: 10px;
        }

        .filter-btn {
            padding: 8px 16px;
            border: 1px solid #ddd;
            background: white;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 14px;
            transition: var(--transition);
        }

        .filter-btn:hover,
        .filter-btn.active {
            background-color: var(--primary);
            color: white;
            border-color: var(--primary);
        }

        /* 表格样式 */
        .data-table {
            background: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            overflow: hidden;
        }

        .table-header {
            background-color: #f8f9fa;
            padding: 20px;
            border-bottom: 1px solid #eaeaea;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .table-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--dark);
        }

        .table-content {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 15px 20px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
        }

        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: var(--dark);
            font-size: 14px;
        }

        tr:hover {
            background-color: #f8f9fa;
        }

        .status-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-active {
            background-color: #d4edda;
            color: #155724;
        }

        .status-inactive {
            background-color: #f8d7da;
            color: #721c24;
        }

        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }

        /* 分页样式 */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
            margin-top: 25px;
        }

        .page-btn {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background: white;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 14px;
            transition: var(--transition);
        }

        .page-btn:hover,
        .page-btn.active {
            background-color: var(--primary);
            color: white;
            border-color: var(--primary);
        }

        .page-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
                height: auto;
            }

            .main-content {
                padding: 20px;
            }

            .search-filter {
                flex-direction: column;
                align-items: stretch;
            }

            .search-box {
                max-width: none;
            }
        }

        /* 模态框样式 */
        .modal {
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            width: 90%;
            max-width: 500px;
            max-height: 90vh;
            overflow-y: auto;
        }

        .modal-header {
            padding: 20px;
            border-bottom: 1px solid #eaeaea;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            margin: 0;
            color: var(--dark);
        }

        .close {
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
            color: var(--secondary);
        }

        .close:hover {
            color: var(--dark);
        }

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            padding: 20px;
            border-top: 1px solid #eaeaea;
            display: flex;
            justify-content: flex-end;
            gap: 12px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--dark);
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-size: 14px;
            transition: var(--transition);
        }

        .form-group input:focus,
        .form-group select:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(74, 107, 255, 0.1);
        }
    </style>
</head>
<body>
<div class="container">
        <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="logo">
            <i class="fas fa-graduation-cap"></i>
            <h1>学海教育</h1>
        </div>

        <div class="user-info">
            <div class="user-avatar" th:text="${#strings.substring(user.username, 0, 1)}">管</div>
            <div>
                <div th:text="${user.username}">管理员</div>
                <div style="font-size: 12px; opacity: 0.8;">系统管理员</div>
            </div>
                <button class="logout-btn" onclick="logout()">
                    <i class="fas fa-sign-out-alt"></i>
                </button>
        </div>

        <ul class="nav-links">
            <li class="active" data-target="user-management">
                <i class="fas fa-users"></i>
                <span>用户管理</span>
            </li>
            <li data-target="course-management">
                <i class="fas fa-book-open"></i>
                <span>课程管理</span>
            </li>
        </ul>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <div class="header">
            <h2>管理员工作台</h2>
                <div class="action-buttons">
                    <button class="btn btn-outline" onclick="testButton()">
                        <i class="fas fa-sync-alt"></i> 刷新数据
                    </button>
                    <button class="btn btn-primary" onclick="testAddUser()">
                        <i class="fas fa-plus"></i> 测试添加用户
                    </button>
                </div>
        </div>

        <!-- 用户管理 -->
        <div class="content-section active" id="user-management">
            <h3 class="section-title">
                <i class="fas fa-users"></i>
                用户管理
            </h3>

            <div class="search-filter">
                <div class="search-box">
                    <i class="fas fa-search"></i>
                        <input type="text" placeholder="搜索用户..." id="userSearch">
                </div>
                    <div class="filter-buttons">
                        <button class="filter-btn active" data-filter="all">全部</button>
                        <button class="filter-btn" data-filter="student">学生</button>
                        <button class="filter-btn" data-filter="teacher">教师</button>
                        <button class="filter-btn" data-filter="admin">管理员</button>
                </div>
            </div>

            <div class="data-table">
                <div class="table-header">
                        <div class="table-title">用户列表</div>
                        <button class="btn btn-primary" onclick="openAddUserModal()">
                            <i class="fas fa-plus"></i> 添加用户
                        </button>
                    </div>
                    <div class="table-content">
                        <table>
                            <thead>
                                <tr>
                                    <th>用户ID</th>
                                    <th>用户名</th>
                                    <th>邮箱</th>
                                    <th>角色</th>
                                    <th>状态</th>
                                    <th>注册时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="userTableBody">
                                <!-- 用户数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="pagination">
                    <button class="page-btn" disabled>
                        <i class="fas fa-chevron-left"></i>
                        </button>
                    <button class="page-btn active">1</button>
                    <button class="page-btn">2</button>
                    <button class="page-btn">3</button>
                    <div class="page-btn">...</div>
                    <button class="page-btn">10</button>
                    <button class="page-btn">
                        <i class="fas fa-chevron-right"></i>
                        </button>
            </div>
        </div>

        <!-- 课程管理 -->
        <div class="content-section" id="course-management">
            <h3 class="section-title">
                <i class="fas fa-book-open"></i>
                课程管理
            </h3>

            <div class="search-filter">
                <div class="search-box">
                    <i class="fas fa-search"></i>
                        <input type="text" placeholder="搜索课程..." id="courseSearch">
                </div>
                    <div class="filter-buttons">
                        <button class="filter-btn active" data-filter="all">全部</button>
                        <button class="filter-btn" data-filter="active">进行中</button>
                        <button class="filter-btn" data-filter="completed">已完成</button>
                        <button class="filter-btn" data-filter="draft">草稿</button>
                </div>
            </div>

            <div class="data-table">
                <div class="table-header">
                        <div class="table-title">课程列表</div>
                    </div>
                    <div class="table-content">
                        <table>
                            <thead>
                                <tr>
                                    <th>课程ID</th>
                                    <th>课程名称</th>
                                    <th>教师</th>
                                    <th>学生数量</th>
                                    <th>状态</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="courseTableBody">
                                <!-- 课程数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="pagination">
                    <button class="page-btn" disabled>
                        <i class="fas fa-chevron-left"></i>
                        </button>
                    <button class="page-btn active">1</button>
                    <button class="page-btn">2</button>
                    <button class="page-btn">3</button>
                    <div class="page-btn">...</div>
                    <button class="page-btn">8</button>
                    <button class="page-btn">
                        <i class="fas fa-chevron-right"></i>
                        </button>
                    </div>
                </div>
                    </div>
                </div>

    <!-- 添加用户模态框 -->
    <div id="addUserModal" class="modal" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3>添加新用户</h3>
                <span class="close" onclick="closeAddUserModal()">&times;</span>
                    </div>
            <div class="modal-body">
                <form id="addUserForm">
                    <div class="form-group">
                        <label for="newUsername">用户名:</label>
                        <input type="text" id="newUsername" name="username" required>
                    </div>
                    <div class="form-group">
                        <label for="newEmail">邮箱:</label>
                        <input type="email" id="newEmail" name="email" required>
                    </div>
                    <div class="form-group">
                        <label for="newPassword">密码:</label>
                        <input type="password" id="newPassword" name="password" required>
                </div>
                    <div class="form-group">
                        <label for="newRole">角色:</label>
                        <select id="newRole" name="roleId" required>
                            <option value="">请选择角色</option>
                            <option value="2">学生</option>
                            <option value="3">教师</option>
                        </select>
                    </div>
                </form>
                        </div>
            <div class="modal-footer">
                <button class="btn btn-outline" onclick="closeAddUserModal()">取消</button>
                <button class="btn btn-primary" onclick="submitAddUser()">添加用户</button>
        </div>
    </div>
</div>

<!-- 编辑用户模态框 -->
    <div id="editUserModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>编辑用户</h3>
                <span class="close" onclick="closeEditUserModal()">&times;</span>
        </div>
        <div class="modal-body">
                <form id="editUserForm">
                    <input type="hidden" id="editUserId" name="userId">
                <div class="form-group">
                        <label for="editUsername">用户名:</label>
                        <input type="text" id="editUsername" name="username" required>
                </div>
                <div class="form-group">
                        <label for="editEmail">邮箱:</label>
                        <input type="email" id="editEmail" name="email" required>
                </div>
                <div class="form-group">
                        <label for="editStatus">状态:</label>
                        <select id="editStatus" name="status" required>
                            <option value="1">启用</option>
                            <option value="0">禁用</option>
                    </select>
                </div>
            </form>
        </div>
        <div class="modal-footer">
                <button class="btn btn-outline" onclick="closeEditUserModal()">取消</button>
                <button class="btn btn-primary" onclick="submitEditUser()">保存修改</button>
        </div>
    </div>
</div>

    <script>
        // 全局函数定义
        function openAddUserModal() {
            console.log('打开添加用户模态框');
            document.getElementById('addUserModal').style.display = 'flex';
            document.getElementById('addUserForm').reset();
        }

        function closeAddUserModal() {
            console.log('关闭添加用户模态框');
            document.getElementById('addUserModal').style.display = 'none';
        }

        function openEditUserModal(userId) {
            console.log('打开编辑用户模态框，用户ID:', userId);
            // 获取用户信息并填充表单
            fetch(`/admin/users/${userId}`)
                .then(response => response.json())
                .then(user => {
                    document.getElementById('editUserId').value = user.id;
                    document.getElementById('editUsername').value = user.username;
                    document.getElementById('editEmail').value = user.email;
                    document.getElementById('editStatus').value = user.status;
                    document.getElementById('editUserModal').style.display = 'flex';
                })
                .catch(error => {
                    console.error('获取用户信息失败:', error);
                    alert('获取用户信息失败');
                });
        }

        function closeEditUserModal() {
            console.log('关闭编辑用户模态框');
            document.getElementById('editUserModal').style.display = 'none';
        }

        function editUser(userId) {
            console.log('编辑用户，ID:', userId);
            openEditUserModal(userId);
        }

        function deleteUser(userId) {
            console.log('删除用户，ID:', userId);
            if (confirm('确定要删除这个用户吗？此操作不可恢复！')) {
                fetch(`/admin/users/${userId}`, {
                    method: 'DELETE'
                })
                .then(response => response.text())
                .then(result => {
                    if (result === 'ok') {
                        alert('用户删除成功！');
                        // 延迟重新加载用户列表，避免重复提示
                        setTimeout(() => {
                            loadUsers();
                        }, 100);
                    } else {
                        alert('删除失败: ' + result);
                    }
                })
                .catch(error => {
                    console.error('删除用户失败:', error);
                    alert('删除失败: ' + error.message);
                });
            }
        }

        function logout() {
            if (confirm('确定要退出登录吗？')) {
                window.location.href = '/logout';
            }
        }

        function testButton() {
            alert('测试按钮工作正常！');
            console.log('测试按钮被点击');
        }

        function testAddUser() {
            console.log('测试添加用户按钮被点击');
            openAddUserModal();
        }

        // 加载用户数据
        function loadUsers() {
            console.log('加载用户数据');
            fetch('/admin/users')
                .then(response => response.json())
                .then(users => {
                    console.log('用户数据加载成功:', users);
                    const userTableBody = document.getElementById('userTableBody');
                    userTableBody.innerHTML = users.map(user => `
                        <tr>
                            <td>${user.id}</td>
                            <td>${user.username}</td>
                            <td>${user.email}</td>
                            <td>${getRoleName(user.roleId)}</td>
                            <td><span class="status-badge status-${user.status === 1 ? 'active' : 'inactive'}">${user.status === 1 ? '活跃' : '非活跃'}</span></td>
                            <td>${formatDate(user.createTime)}</td>
                            <td>
                                <button class="btn btn-outline" onclick="editUser(${user.id})">
                                    <i class="fas fa-edit"></i> 编辑
                                </button>
                                <button class="btn btn-danger" onclick="deleteUser(${user.id})">
                                    <i class="fas fa-trash"></i> 删除
                                </button>
                            </td>
                        </tr>
                    `).join('');
                })
                .catch(error => {
                    console.error('加载用户数据失败:', error);
                    document.getElementById('userTableBody').innerHTML = '<tr><td colspan="7" style="text-align: center;">加载失败</td></tr>';
                });
        }

        // 加载课程数据
        function loadCourses() {
            console.log('加载课程数据');
            fetch('/admin/courses')
                .then(response => response.json())
                .then(courses => {
                    console.log('课程数据加载成功:', courses);
                    const courseTableBody = document.getElementById('courseTableBody');
                    courseTableBody.innerHTML = courses.map(course => `
                        <tr>
                            <td>${course.id}</td>
                            <td>${course.title || '无标题'}</td>
                            <td>${course.teacherName || '未知'}</td>
                            <td>${course.studentCount || 0}</td>
                            <td><span class="status-badge status-${getCourseStatusClass(course.status)}">${getCourseStatusText(course.status)}</span></td>
                            <td>${formatDate(course.createdAt)}</td>
                            <td>
                                <button class="btn btn-outline" onclick="editCourse(${course.id})">
                                    <i class="fas fa-edit"></i> 编辑
                                </button>
                                <button class="btn btn-danger" onclick="deleteCourse(${course.id})">
                                    <i class="fas fa-trash"></i> 删除
                                </button>
                            </td>
                        </tr>
                    `).join('');
                })
                .catch(error => {
                    console.error('加载课程数据失败:', error);
                    document.getElementById('courseTableBody').innerHTML = '<tr><td colspan="7" style="text-align: center;">加载失败</td></tr>';
                });
        }

        // 获取角色名称
        function getRoleName(roleId) {
            const roleMap = {
                2: '学生',
                3: '教师',
                1: '管理员'
            };
            return roleMap[roleId] || '未知';
        }

        // 获取课程状态文本
        function getCourseStatusText(status) {
            const statusMap = {
                0: '草稿',
                1: '发布',
                2: '下架'
            };
            return statusMap[status] || '未知';
        }

        // 获取课程状态样式类
        function getCourseStatusClass(status) {
            const classMap = {
                0: 'pending',
                1: 'active',
                2: 'inactive'
            };
            return classMap[status] || 'inactive';
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未知';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN');
        }

        // 课程操作函数 - 全局作用域
        function editCourse(courseId) {
            console.log('编辑课程，ID:', courseId);
            // 先获取课程详情
            fetch(`/admin/courses/${courseId}`)
                .then(response => response.json())
                .then(course => {
                    console.log('获取到课程信息:', course);
                    const newTitle = prompt('请输入新的课程名称:', course.title || '');
                    if (newTitle && newTitle.trim() && newTitle !== course.title) {
                        const newDescription = prompt('请输入新的课程描述:', course.description || '');
                        if (newDescription && newDescription.trim()) {
                            updateCourse(courseId, {
                                title: newTitle.trim(),
                                description: newDescription.trim()
                            });
                        }
                    }
                })
                .catch(error => {
                    console.error('获取课程详情失败:', error);
                    alert('获取课程信息失败');
                });
        }

        function updateCourse(courseId, courseData) {
            fetch(`/admin/courses/${courseId}/update`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(courseData)
            })
            .then(response => response.text())
            .then(result => {
                if (result === 'ok') {
                    alert('课程信息更新成功！');
                    loadCourses();
                } else {
                    alert('更新失败: ' + result);
                }
            })
            .catch(error => {
                console.error('更新课程失败:', error);
                alert('更新失败: ' + error.message);
            });
        }

        function deleteCourse(courseId) {
            console.log('删除课程，ID:', courseId);
            if (confirm('确定要删除这个课程吗？此操作将删除课程及其所有章节和课件，不可恢复！')) {
                fetch(`/admin/courses/${courseId}`, {
                    method: 'DELETE'
                })
                .then(response => response.text())
                .then(result => {
                    console.log('删除结果:', result);
                    if (result === 'ok') {
                        alert('课程删除成功！');
                        loadCourses();
                    } else {
                        alert('删除失败: ' + result);
                    }
                })
                .catch(error => {
                    console.error('删除课程失败:', error);
                    alert('删除失败: ' + error.message);
                });
            }
        }


        function submitAddUser() {
            console.log('提交添加用户表单');
            const form = document.getElementById('addUserForm');
            const formData = new FormData(form);
            const userData = {
                username: formData.get('username'),
                email: formData.get('email'),
                password: formData.get('password'),
                roleId: parseInt(formData.get('roleId'))
            };

            console.log('用户数据:', userData);

            fetch('/admin/users/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(userData)
            })
            .then(response => response.text())
            .then(result => {
                console.log('添加用户结果:', result);
                if (result === 'ok') {
                    alert('用户添加成功！');
                    closeAddUserModal();
                    // 延迟重新加载用户列表，避免重复提示
                    setTimeout(() => {
                        loadUsers();
                    }, 100);
                } else {
                    alert('添加失败: ' + result);
                }
            })
            .catch(error => {
                console.error('添加用户失败:', error);
                alert('添加失败: ' + error.message);
            });
        }

        function submitEditUser() {
            console.log('提交编辑用户表单');
            const form = document.getElementById('editUserForm');
            const formData = new FormData(form);
            const userId = formData.get('userId');
            const userData = {
                username: formData.get('username'),
                email: formData.get('email'),
                status: parseInt(formData.get('status'))
            };

            console.log('编辑用户数据:', userData);

            fetch(`/admin/users/${userId}/update`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(userData)
            })
            .then(response => response.text())
            .then(result => {
                console.log('编辑用户结果:', result);
                if (result === 'ok') {
                    alert('用户信息更新成功！');
                    closeEditUserModal();
                    // 延迟重新加载用户列表，避免重复提示
                    setTimeout(() => {
                        loadUsers();
                    }, 100);
                } else {
                    alert('更新失败: ' + result);
                }
            })
            .catch(error => {
                console.error('更新用户失败:', error);
                alert('更新失败: ' + error.message);
            });
        }

        document.addEventListener('DOMContentLoaded', function() {
            // 导航切换
            const navLinks = document.querySelectorAll('.nav-links li');
            const contentSections = document.querySelectorAll('.content-section');

            navLinks.forEach(link => {
                link.addEventListener('click', function() {
                    // 移除所有活跃状态
                    navLinks.forEach(l => l.classList.remove('active'));
                    contentSections.forEach(section => section.classList.remove('active'));

                    // 添加活跃状态
                    this.classList.add('active');
                    const targetId = this.getAttribute('data-target');
                    document.getElementById(targetId).classList.add('active');
                });
            });






            // 搜索功能
            document.getElementById('userSearch').addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                const rows = document.querySelectorAll('#userTableBody tr');
                rows.forEach(row => {
                    const text = row.textContent.toLowerCase();
                    row.style.display = text.includes(searchTerm) ? '' : 'none';
                });
            });

            document.getElementById('courseSearch').addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                const rows = document.querySelectorAll('#courseTableBody tr');
                rows.forEach(row => {
                    const text = row.textContent.toLowerCase();
                    row.style.display = text.includes(searchTerm) ? '' : 'none';
                });
            });

            // 筛选功能
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    
                    const filter = this.getAttribute('data-filter');
                    // 这里可以根据筛选条件过滤数据
                    console.log('筛选条件:', filter);
                });
            });

            // 点击模态框外部关闭
            window.onclick = function(event) {
                const addUserModal = document.getElementById('addUserModal');
                const editUserModal = document.getElementById('editUserModal');
                if (event.target === addUserModal) {
                    closeAddUserModal();
                }
                if (event.target === editUserModal) {
                    closeEditUserModal();
                }
            }

            // 初始加载
            loadUsers();
            loadCourses();
        });
    </script>
</body>
</html>